<?php
class SchedulesController extends AppController {

	var $name = 'Schedules';
	//var $name = 'ControllerName';
	var $components = array('RemoteParser','ScheduleFunctions');
	function index($strMode = "full", $intBWMode = 0, $strExtendedOptions = "45;W1;C1;L1;P1;S1")
	{

		$this->Day = ClassRegistry::init('Day');
		$this->Course = ClassRegistry::init('Course');
		$this->Mode = ClassRegistry::init('Mode');

		//$this->Session->setFlash('test');
		$arrExtOptions = explode(";", $strExtendedOptions);
		$arrSchedule = $this->Schedule->Classe->find('all', array('conditions' => array('instructor LIKE' => '%Malski%'),'order' => array('day_id ASC', 'row ASC', 'position ASC'),));
		if($strMode == "full123")
		{
			//$arrSchedule = $this->Schedule->Classe->find('all', array('conditions' => array('schedule_id' => $arrExtOptions[0])));
		}
		else
		{
			//$arrSchedule = $this->Schedule->Classe->find('all', array('conditions' => array('AND' => array('schedule_id' => $arrExtOptions[0]), 'OR' => array(array('group' => $arrExtOptions[1]),array('group' => $arrExtOptions[2]),array('group' => $arrExtOptions[3]),array('group' => $arrExtOptions[4]),array('group' => $arrExtOptions[5])))));
		}
		debug($arrSchedule);
		$this->set('arrDays', $this->Day->find('all'));
		$this->set('strCourseName', $this->ScheduleFunctions->id_to_CourseName($arrSchedule[0]['Schedule']['course_id']));
		$this->set('strMode', $this->ScheduleFunctions->id_to_modeName($arrSchedule[0]['Schedule']['mode_id']));
		$this->set('intBWMode', $intBWMode);
		$this->set('strDisplayMode', $strMode);
		$this->set('strExtendedOptions', $strExtendedOptions);
		$this->set('data', $arrSchedule);
	}
	function parsing_data() {

		if (!$this->RemoteParser->openRemoteFile('http://www.pwsz.nysa.pl/plany/plany.php')) {
			$err_str = 'oops lets check our internet connection, HTTP_CODE: ';
			$err_str .= $this->RemoteParser->getExecutionInfo('http_code');
			die($err_str);
		}
		$arrMessage = array();
		$arrCollegeId = array();
		//parsujemy kod html aby wydobyc liste z planami
		while(($parsing_data = $this->RemoteParser->readFromTo('<a href="planWydruk.php?NrKier=', 'target=')) !== false) {
			preg_match('%[0-9]{1,3}%', $parsing_data, $matches);
			$arrCollegeId[] = $matches[0];
			

		}
		//debug($arrCollegeId);
		$intCollegaIdCounter = 0;
		while(isset($arrCollegeId[$intCollegaIdCounter]))
		{
		//$intCollegeId = 90;

		if (!$this->RemoteParser->openRemoteFile('http://www.pwsz.nysa.pl/plany/planWydruk.php?NrKier='.$arrCollegeId[$intCollegaIdCounter])) {
			$err_str = 'oops lets check our internet connection, HTTP_CODE: ';
			$err_str .= $this->RemoteParser->getExecutionInfo('http_code');
			die($err_str);
		}
		$schedule_data = array();
		//parsujemy kod html aby wydobyc informacje o planie
		while(($parsing_data = $this->RemoteParser->readFromTo('font size="+1">', '</font')) !== false) {
			preg_match('%.*%', $parsing_data, $matches);
			$schedule_data[] = $matches;
		}
		$blnAddSchedule = false;
		if($arrRecord = $this->Schedule->find('first', array('conditions' => array('college_id' => $arrCollegeId[$intCollegaIdCounter]))))
		{
			//debug($arrRecord);
			$dtExistingDate = new DateTime($arrRecord['Schedule']['date']);
			$dtNewDate = new DateTime($schedule_data[3][0]);
			if($dtNewDate > $dtExistingDate)
			{
				$arrMessage[] = 'Zaktualizowano plan dla: '.iconv("CP1250", "UTF-8", $schedule_data[0][0]).' tryb:'.$schedule_data[1][0].' semestr:'.$schedule_data[2][0].' data aktualizacji:'.$schedule_data[3][0];
				$this->Schedule->delete($arrRecord['Schedule']['id'], true);
				$blnAddSchedule = true;
			}
		}
		else {
			$blnAddSchedule = true;
		}
		if($blnAddSchedule)
		{
			$arrClassesList = array();
			$arrLegendList = array();
			$test = array();
			//parsujemy kod html aby wydobyc infomracje o zajeciach
			while(($parsing_data = $this->RemoteParser->readFromTo('td', '/td')) !== false) {
				preg_match('%Poniedzialek|Wtorek|Sroda|Czwartek|Piatek|Sobota|Niedziela|(colspan="(.)">)?((.)(.), ([^"<>]*, ){3,6}([0-9a-zA-ZąćęłńóśźżĄĆĘŁŃÓŚŹŻ. :/]*))%', $parsing_data, $matches);
				if(isset($matches[3]) && $matches[3] != null)
				{
					$test = mb_split(', ',$matches[3]);
				 	$matches[9] = $test[1];
				}
				 $arrClassesList[] = $matches;
				preg_match('%([^"<>]*)</b> = ([^"<>]*)%', $parsing_data, $matches2);
				if(isset($matches2[0]) && $matches2[0] != null)
				{
					$arrLegendList[iconv("CP1250", "UTF-8",$matches2[1])] = iconv("CP1250", "UTF-8",$matches2[2]);
				}
			}
			
			$Classe = array();
			$Schedule = array (	'course_id' => $this->ScheduleFunctions->courseName_to_id(iconv("CP1250", "UTF-8",$schedule_data[0][0])),
								'mode_id' => $this->ScheduleFunctions->modeName_to_id($schedule_data[1][0]),
								'semester' => $schedule_data[2][0],
								'date'=> $schedule_data[3][0],
								'college_id'=> $arrCollegeId[$intCollegaIdCounter]);
			$arrMessage[] = 'Dodaje nowy plan do bazy dla: '.iconv("CP1250", "UTF-8", $schedule_data[0][0]).' tryb:'.$schedule_data[1][0].' semestr:'.$Schedule['semester'].' id:'.$Schedule['college_id'].' data:'.$Schedule['date'];
			$intCount = 26;
			while(isset($arrClassesList[$intCount]) && $arrClassesList[$intCount] !== null) {
				if(isset($arrClassesList[$intCount][0]) && $arrClassesList[$intCount][0]=='Poniedzialek')
				{
					//debug('Poniedzialek');
					$intPosition = 0;
					$intDay = 1;
					$intRow = 1;
					
				} elseif(isset($arrClassesList[$intCount][0]) && $arrClassesList[$intCount][0]=='Wtorek')
				{
					//debug('Wtorek');
					$intPosition = 0;
					$intDay = 2;
					$intRow = 1;
				}elseif(isset($arrClassesList[$intCount][0]) && $arrClassesList[$intCount][0]=='Sroda')
				{
					//debug('Sroda');
					$intPosition = 0;
					$intDay = 3;
					$intRow = 1;
				}elseif(isset($arrClassesList[$intCount][0]) && $arrClassesList[$intCount][0]=='Czwartek')
				{
					//debug('Czwartek');
					$intPosition = 0;
					$intDay = 4;
					$intRow = 1;
				}elseif(isset($arrClassesList[$intCount][0]) && $arrClassesList[$intCount][0]=='Piatek')
				{
					//debug('Piatek');
					$intPosition = 0;
					$intDay = 5;
					$intRow = 1;
				}elseif(isset($arrClassesList[$intCount][0]) && $arrClassesList[$intCount][0]=='Sobota')
				{
					//debug('Sobota');
					$intPosition = 0;
					$intDay = 6;
					$intRow = 1;
				}elseif(isset($arrClassesList[$intCount][0]) && $arrClassesList[$intCount][0]=='Niedziela')
				{
					//debug('Niedziela');
					$intPosition = 0;
					$intDay = 7;
					$intRow = 1;
				}elseif(isset($arrClassesList[$intCount][1]))
				{
					
					$strWeekType = substr($arrClassesList[$intCount][6], 0, 2);
					if( $strWeekType != 'tn' && $strWeekType != 'tp' && $strWeekType != 'tz' &&
					 	$strWeekType != 'zn' && $strWeekType != 'zp' && $strWeekType != 'zz')
					{
						$strWeekType = substr($arrClassesList[$intCount][7], 0, 2);
						if( $strWeekType != 'tn' && $strWeekType != 'tp' && $strWeekType != 'tz' &&
					 		$strWeekType != 'zn' && $strWeekType != 'zp' && $strWeekType != 'zz')
						{
							$strWeekType = '';
						}
					}
					$strClassData = explode(", ", iconv("CP1250", "UTF-8",$arrClassesList[$intCount][3]));
					if(is_numeric($strClassData[3][0]))
					{
						$strInstructor = $strClassData[2];
						$strRoomNo = $strClassData[3];
						$strSelectiveWeeks = @$strClassData[5];
					}
					else
					{
						$strInstructor = $strClassData[3].' '.$strClassData[2];
						$strRoomNo = $strClassData[4];
						$strSelectiveWeeks = @$strClassData[6];
					}
					$Classe[] = array('schedule_id' => 1,
						'day_id' => $intDay,
						'row' => $intRow,
						'group' => $arrClassesList[$intCount][4].$arrClassesList[$intCount][5],
						'position' => $intPosition,
						'length' => $arrClassesList[$intCount][2],
						'name' => iconv("CP1250", "UTF-8",$arrClassesList[$intCount][3]),
						'short_name' => $strClassData[1],
						'full_name' => @$arrLegendList[iconv("CP1250", "UTF-8", $arrClassesList[$intCount][9])],
						'instructor' => $strInstructor,
						'room_no' => $strRoomNo,
						'week_type' => $strWeekType,
						'selective_weeks' => @substr(@$strSelectiveWeeks, 5));
					
					$intPosition+=$arrClassesList[$intCount][2]-1;
	
				}
				if($intPosition>=17)
				{
					$intPosition = 0;
					$intRow++;
				}
				$intPosition++;
				$intCount++;
			}
	
			$data['Classe'] =$Classe;
			$data['Schedule'] =$Schedule;
			$this->Schedule->saveAll($data);
			}
			$intCollegaIdCounter++;

		}
		$this->set('message', $arrMessage);
	
		//debug($this->Schedule->Classe->find('first'));
		//debug($intCount);
		//debug($schedule_data);
		//debug($arrClassesList);
		//$this->autoRender = false;
	}
}
?>